<?php

namespace plugin\coleopenapi\app\admin\controller;

use app\common\controller\BaseAdminController;
use plugin\coleopenapi\app\admin\validate\ApiLogicValidate;
use plugin\coleopenapi\app\logic\ApiLogic;
use plugin\coleopenapi\client\OpenApiClient;

class ApiController extends BaseAdminController
{
    protected function init()
    {
        parent::init();
        $this->logic = new ApiLogic();
        $this->validate = new ApiLogicValidate();
    }

    protected function searchWhere()
    {
        $where = [];
        $this->form['method'] && $where[] = ['method', 'like', "%{$this->form['method']}%"];
        $this->form['title'] && $where[] = ['title', 'like', "%{$this->form['title']}%"];
        $this->form['module'] && $where[] = ['module', '=', $this->form['module']];
        !is_null($this->form['status']) && $this->form['status'] != "" && $where[] = ['status', '=', $this->form['status']];
        return $where;
    }

    public function afterUpdate($type, &$data)
    {
        if ($type == self::UPDATE) {
            $this->logic->removeCache();
        }
    }

    public function remove()
    {
        $ids = request()->input('ids', [request()->input($this->idKey)]);
        if (!empty($ids)) {
            $this->logic->where(['id', 'in', $ids])->delete();
            $this->logic->removeCache();
            return $this->success();
        } else {
            return $this->error('参数错误，请检查');
        }
    }

    public function changeStatus()
    {
        $data = parent::changeStatus();
        $this->logic->removeCache();
        return $data;
    }

    public function test()
    {
        $data = input('data');
        $method = input('method');
        $sdk = new OpenApiClient();
        $sdk->config([
            'api' => input('api', ''),
            'app_key' => input('app_key', ''),
            'app_secret' => input('app_secret', ''),
        ]);
        $res = $sdk->post($method, json_decode($data, true));
        return $this->success($res);
    }
}
